package com.ouman.luoliluoli;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.CardView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.ouman.luoliluoli.models.DaysModel;
import com.ouman.luoliluoli.models.UserInfo;
import com.ouman.luoliluoli.utils.GlobalConstants;
import com.ouman.luoliluoli.utils.LocalSaveHelper;

import org.w3c.dom.Text;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import static android.app.Activity.RESULT_CANCELED;


public class UserInfoFragment extends Fragment {

    private OnFragmentInteractionListener mListener;

    private TextView textViewName;
    private TextView textViewGender;
    private TextView textViewBirth;
    private TextView textViewSign;
    private TextView textViewEmail;
    private ImageView imageViewAvatar;
    private Button buttonUpdate;
    private boolean isEdit = false;

    private UserInfo userInfo;
    private LocalSaveHelper localSaveHelper;
    private String STORAGE_NAME = "userInfo";

    private CardView cardViewAvatar;

    private CardView cardViewPart1;
    private CardView cardViewPart2;
    private CardView cardViewPart3;
    private CardView cardViewPart4;
    private CardView cardViewPart5;

    private static final int CAMERA_CODE = 1;
    private static final int GALLERY_CODE = 2;
    private static final int CROP_CODE = 3;
    private long nowTime;
    private File avatarImageFile;



    private GlobalConstants globalConstants;



    public UserInfoFragment() {
        // Required empty public constructor
    }

    public static UserInfoFragment newInstance(String param1, String param2) {
        UserInfoFragment fragment = new UserInfoFragment();
        Bundle args = new Bundle();

        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_user_info, container, false);
//        ((AppCompatActivity)getActivity()).getSupportActionBar().setTitle("我的资料");
//        ((MainActivity) getActivity()).hideFloatingActionButton();
        localSaveHelper = new LocalSaveHelper();

        textViewName = (TextView) view.findViewById(R.id.textViewName);
        textViewGender = (TextView) view.findViewById(R.id.textViewGender);
        textViewBirth = (TextView) view.findViewById(R.id.textViewBirth);
        textViewSign = (TextView) view.findViewById(R.id.textViewSign);
        textViewEmail = (TextView) view.findViewById(R.id.textViewEmail);
        imageViewAvatar = (ImageView) view.findViewById(R.id.imageViewAvatar);
        buttonUpdate = (Button) view.findViewById(R.id.buttonUpdate);

        cardViewAvatar = (CardView) view.findViewById(R.id.cardViewAvatar);
        cardViewPart1 = (CardView) view.findViewById(R.id.cardViewPart1);
        cardViewPart2 = (CardView) view.findViewById(R.id.cardViewPart2);
        cardViewPart3 = (CardView) view.findViewById(R.id.cardViewPart3);
        cardViewPart4 = (CardView) view.findViewById(R.id.cardViewPart4);
        cardViewPart5 = (CardView) view.findViewById(R.id.cardViewPart5);

        cardViewAvatar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, GALLERY_CODE);
            }
        });

        cardViewPart1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                View popDialogView = LayoutInflater.from(getContext()).inflate(R.layout.userinfo_edit_name_popup_dialog, null);
                final EditText editTextName = (EditText) popDialogView.findViewById(R.id.editTextName);
                final AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
                builder.setView(popDialogView);
                builder.setTitle("修改姓名");
                builder.setPositiveButton("确认修改", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        // 把添加时间保存到internal storage中， 我们在saveToInternalStorage
                        // 中已经设置了保存方式为APPEND，因此不会覆盖而是追加
                        String newName = editTextName.getText().toString();
                        userInfo.setNickName(newName);
                        textViewName.setText(newName);
                        isEdit = true;
                    }
                });
                builder.show();
            }
        });
        cardViewPart2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(getContext(), "性别不支持修改哦", Toast.LENGTH_SHORT).show();
            }
        });
        cardViewPart3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(getContext(), "生日不支持修改哦", Toast.LENGTH_SHORT).show();
            }
        });
        cardViewPart4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                View popDialogView = LayoutInflater.from(getContext()).inflate(R.layout.userinfo_edit_sign_popup_dialog, null);
                final EditText editTextSign = (EditText) popDialogView.findViewById(R.id.editTextSign);
                final AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
                builder.setView(popDialogView);
                builder.setTitle("修改个性签名");
                builder.setPositiveButton("确认修改", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        // 把添加时间保存到internal storage中， 我们在saveToInternalStorage
                        // 中已经设置了保存方式为APPEND，因此不会覆盖而是追加
                        String newSign = editTextSign.getText().toString();
                        userInfo.setSign(newSign);
                        textViewSign.setText(newSign);
                        isEdit = true;
                    }
                });
                builder.show();

            }
        });
        cardViewPart5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(getContext(), "邮箱不支持修改哦", Toast.LENGTH_SHORT).show();
            }
        });

        try{
            userInfo = localSaveHelper.readUserInfoFromInternalStorage(getActivity(), STORAGE_NAME);
            if (userInfo != null){
                System.out.println("获取到了本地用户信息");
                // 说明本地有数据，那就显示数据把
                textViewName.setText(userInfo.getNickName());
                textViewSign.setText(userInfo.getSign());
                textViewGender.setText(userInfo.getGender());
                textViewEmail.setText(userInfo.getEmail());
                textViewBirth.setText(userInfo.getBirthday());

                String imageUrl = userInfo.getAvatarUrl();
                Glide.clear(imageViewAvatar);
                Glide.with(getActivity())
                        .load(imageUrl)
                        .asBitmap()
                        .error(R.drawable.avatar1)
                        .into(imageViewAvatar);
            }

        }catch (IOException e){
            Toast.makeText(getActivity(), "获取用户信息错误, something was wrong?!!", Toast.LENGTH_SHORT).show();

        }

        buttonUpdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isEdit){
                    upDateUserInfo(userInfo, "test");
                }else{
                    Toast.makeText(getActivity(), "未作更改", Toast.LENGTH_SHORT).show();
                }

            }
        });



        final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());

        Button signOut = (Button) view.findViewById(R.id.button_sign_out);
        signOut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                builder.setMessage("确定要退出登陆吗？");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        SharedPreferences.Editor editor = preferences.edit();
                        editor.putBoolean("isLogin", false);
                        editor.apply();

                        // getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                                // new UserFragment()).commit();
                        getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container_user,
                                new UserFragment()).commit();
                    }
                });
                builder.setNegativeButton("按错了", null);
                builder.show();
            }
        });


        return view;
    }

    private void upDateUserInfo(UserInfo userInfo, String msg){
        // this method will update user info both local and server
        localSaveHelper = new LocalSaveHelper();
        localSaveHelper.saveToInternalStorage(userInfo, "userInfo", getActivity(), Context.MODE_PRIVATE);
        Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show();
    }


    //调用系统相册选取重写这个方法
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case GALLERY_CODE:
                if (resultCode == RESULT_CANCELED) {
                    Toast.makeText(getActivity(), "取消了从相册选择", Toast.LENGTH_LONG).show();
                    return;
                }

                try {
                    Uri imageUri = data.getData();
                    System.out.println(imageUri);
                    System.out.println("====!!!!!! uri---" + imageUri.getPath());
                    String realPath = getRealPathFromUri(getActivity(), imageUri);
                    System.out.println("====!!!!!! realpath----" + realPath);
//                    avatarImageFile = new File(realPath);
                    cropImage(imageUri);

                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case CROP_CODE:
                try {
                    if(data!=null) {
                        Bundle extras = data.getExtras();
                        Bitmap bm = extras.getParcelable("data");
                        imageViewAvatar.setImageBitmap(bm);
                        isEdit = true;

                        Uri uri = getImageFile(bm);
                        //也可以直接将绝对路径转为文件
                        System.out.println("croped image url: " + uri);
                        System.out.println("try another path: " + uri.getPath());
                        String realPath = uri.getPath();
                        System.out.println("croped image real path: " + realPath);
                        avatarImageFile = new File(realPath);
                    }else {
                        Toast.makeText(getActivity(), "some error crop image", Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    private void cropImage(Uri uri){
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", true);
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, CROP_CODE);
    }
    public Uri getImageFile(Bitmap bm) {
        byte[] bytes;
        ByteArrayOutputStream stream;
        String filePath;
        // 图片允许最大空间 单位：KB
        double maxSize = 100;
        stream = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 100, stream);
        bytes = stream.toByteArray();
        // 将字节换成KB
        double mid = bytes.length / 1024;
        // 判断bitmap占用空间是否大于允许最大空间 如果大于则压缩 小于则不压缩
        if (mid > maxSize) {
            // 获取bitmap大小 是允许最大大小的多少倍
            double i = mid / maxSize;
            // 开始压缩 此处用到平方根 将宽带和高度压缩掉对应的平方根倍
            // （1.保持刻度和高度和原bitmap比率一致，压缩后也达到了最大大小占用空间的大小）
            bm = zoomImage(bm, bm.getWidth() / Math.sqrt(i), bm.getHeight() / Math.sqrt(i));
            stream = new ByteArrayOutputStream();
            bm.compress(Bitmap.CompressFormat.PNG, 100, stream);
            bytes = stream.toByteArray();
        }
        Uri uri = saveBitmap(bm);
        return uri;
    }
    public Uri saveBitmap(Bitmap bm) {
        File tmpDir = new File(Environment.getExternalStorageDirectory() + "/com.ouman.luoliluoli");//新建文件夹用来保存图片，地址自己写
        if (!tmpDir.exists()) {
            tmpDir.mkdir();
        }//如果地址不存在，则新建
        if (nowTime == 0) {
            nowTime = System.currentTimeMillis();
        }//获取系统时间
        File img = new File(tmpDir.getAbsolutePath() + "/" + nowTime + ".png");
        try {
            FileOutputStream fos = new FileOutputStream(img);
            bm.compress(Bitmap.CompressFormat.PNG, 85, fos);//压缩文件
            fos.flush();
            fos.close();
            return Uri.fromFile(img);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static Bitmap zoomImage(Bitmap bgimage, double newWidth, double newHeight) {
        float width = bgimage.getWidth();
        float height = bgimage.getHeight();
        Matrix matrix = new Matrix();
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap bitmap = Bitmap.createBitmap(bgimage, 0, 0, (int) width, (int) height, matrix, true);
        return bitmap;
    }

    public static String getRealPathFromUri(Context context, Uri contentUri) {
        /* this method get real path from Uri*/
        Cursor cursor = null;
        try {
            String[] proj = { MediaStore.Images.Media.DATA };
            cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }



    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }


    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}
